package com.edushare.common.dao;

import java.util.List;

import com.edushare.common.orm.ORMInterface;
import com.edushare.common.vo.GradeKey;
import com.edushare.common.vo.GradingItem;
import com.edushare.common.vo.ItemGrade;
import com.edushare.common.vo.Users;

public class ItemGradeDAO extends CayenneBasedDAO {

	public ItemGradeDAO(ORMInterface ormInterface) {
		super(ormInterface);
	}

	public void removeUserGrade(Users user, GradingItem item){
		ItemGrade itemGrd = getUserGrade(user, item);
		if(itemGrd == null)
			return;
		getDataContext().deleteObject(itemGrd);
		getDataContext().commitChanges();
	}
	
	public void addUserGrade(Users user, GradingItem item, String comments,
			Double marks, GradeKey grade) {
		ItemGrade itemGrd = getUserGrade(user, item);
		if(itemGrd == null){
			itemGrd = new ItemGrade();
			getDataContext().registerNewObject(itemGrd);
		}
		itemGrd.setUser(user);
		itemGrd.setComments(comments);
		itemGrd.setGradingItem(item);
		itemGrd.setMarks(marks);
		itemGrd.setGradeKey(grade);
		getDataContext().commitChanges();
	}
	
	public ItemGrade getUserGrade(Users user, GradingItem item) {
		List<ItemGrade> gradeList = item.getGrades();
		for(ItemGrade it:gradeList){
			if(it.getUser() == user)
				return it;
		}
		return null;
	}
	
	public List<ItemGrade> getItemGrades(GradingItem item){
		return item.getGrades();
	}
}
